package edu.sysu.demo.petstore.dog.web.rest;

import com.google.common.io.BaseEncoding;
import edu.sysu.demo.petstore.dog.data.entity.Key.KeyType;
import edu.sysu.demo.petstore.dog.key.KeyManagementException;
import edu.sysu.demo.petstore.dog.key.KeyService;
import java.security.PublicKey;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/key/public")
public class KeyController {

  private final KeyService keyService;

  private final BaseEncoding baseEncoding;

  @Autowired
  public KeyController(KeyService keyService, BaseEncoding baseEncoding) {
    this.keyService = keyService;
    this.baseEncoding = baseEncoding;
  }

  @GetMapping
  public String publicKey() {
    PublicKey publicKey = keyService.query("issue_key", KeyType.RSA_PUBLIC);
    return Optional.ofNullable(publicKey)
        .map(PublicKey::getEncoded)
        .map(baseEncoding::encode)
        .orElseThrow(KeyManagementException::new);
  }
}
